/**
 * 获取host域名
 * @returns
 */
function hostUrl() {
    var storeId = 3578748;
    var pathname = location.pathname;
    if (pathname) {
        var urlArray = pathname.split('/');
        var regPos = /^\d+(\.\d+)?$/;
        if (regPos.test(urlArray[1])) {
            storeId = urlArray[1];
        }
    }
    return location.protocol+'//'+location.host+'/'+storeId+'/home/';
}

/**
 *返回历史记录上一页，如果没有则指定返回页面
 * @param redirect 指定返回页面
 */
function goHistoryBack(redirect)
{
    if (history.length > 1) {
        window.history.go(-1);
    } else {
        if (!redirect) {
            redirect = location.protocol+'//'+location.host+'/';
        }
        window.location.href = redirect;
    }
}

/**
 * 获取url中的参数，返回指定参数
 * @param name
 * @returns {*}
 */
function getQueryString(name)
{
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");// 匹配目标参数
    var r = window.location.search.substr(1).match(reg); // 对querystring匹配目标参数
    if (r != null) return unescape(r[2]);
    return null;
}

/**
 * 获取url中的参数，返回数组
 */
function getQueryArray()
{
    var qs = location.search.substr(1), // 获取url中"?"符后的字串
        args = {}, // 保存参数数据的对象
        items = qs.length ? qs.split("&") : [], // 取得每一个参数项,
        item = null,
        len = items.length;
    for (var i = 0; i < len; i++) {
        item = items[i].split("=");
        var name = decodeURIComponent(item[0]),
            value = decodeURIComponent(item[1]);
        if (name) {
            args[name] = value;
        }
    }
    return args;
}

function alertMessage(msg)
{
    if ($('#timing-msg').size() == 0) {
        var tag = '<div class="am-modal am-modal-no-btn pahod-alert am-modal-active" tabindex="-1" id="timing-msg">' + msg + '</div>';
        $('body').append(tag);
    }
    setTimeout(function () {
        $('#timing-msg').remove();
    }, 2000);
}

function myalert(msg)
{
    $('#my-alert').remove();
    var confirm = arguments[1] ? arguments[1] : '知道了';
    var tag = '<div class="alert-explain am-modal" tabindex="-1" id="my-alert"><p>' + msg + '</p><div class="am-modal-footer"><span class="am-modal-btn">' + confirm + '</span></div></div>';
    $('body').append(tag);
    $('#my-alert').modal({'closeViaDimmer': false});
}

/**
 * 上传图片
 * @param file 需要上传的文件
 * @param callback 回调函数 接受参数url
 */
function upLoadImg(file, callback)
{
    var file = file;
    var form = new FormData();
    form.append('files', file);
    $.ajax({
        type: 'post',
        dataType: 'json',
        url: hostUrl() + 'files/upload_image',
        data: form,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success: function(res) {
            console.log(res);
            if (res.status) {
                if (typeof callback === 'function') {
                    callback(res.data);
                }
            } else {
                alert(res.msg);
            }
        },
        error: function(e) {
            alert('网络错误');
        }
    });
}

$(document).ready(function () {
    //lazyload
    $('img.lazy').lazyload({skip_invisible: false});

    //地址定位
    function geoLocationCity(hands)
    {
        //防止重复调用 - start
        var cookie = $.AMUI.utils.cookie;
        var geoCount = cookie.get('geoCount') ? parseInt(cookie.get('geoCount')) : 0;
        if (geoCount >= 2) {
            return;
        }
        geoCount = geoCount + 1;
        cookie.set('geoCount', geoCount, 43200, '/', location.host.substring(location.host.indexOf('.') + 1));
        //防止重复调用 - end

        var geolocation = new jQuery.AMUI.Geolocation({
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 60000
        });

        geolocation.get().then(function (position) {
            var coords = position.coords.latitude + ',' + position.coords.longitude;
            if (coords) {
                $.ajax({
                    type: 'GET',
                    dataType: 'json',
                    async: false,
                    url: hostUrl() + 'home/ajaxCurrentCity',
                    data: {
                        location: coords, //经度，纬度，例如：39.983424,116.322987
                        coordtype: 'wgs84ll',
                        output: 'json',
                        pois: 0
                    },
                    beforeSend: function() {

                    },
                    success: function (json) {
                        if (hands) {//手动定位
                            $('#position-city').text(json.msg.city);
                            if ($('.freeTravalCity').size() > 0) {
                                $('.city-page').hide();
                                $('.main-page').show();
                                $('.Head-cont-center span').text(json.msg.city);
                                $('.freeTravel-page .city').attr('data-city-name', json.msg.city);
                                $('.freeTravel-nav li.am-active').trigger('click');
                            }
                        } else {
                            if (json.messages) {
                                if (confirm('当前定位城市为：' + json.msg.city + '，是否切换？')) {
                                    window.location.href = window.location.href;
                                }
                            }
                        }
                    }
                });

                if (geolocation.watchID) {
                    geolocation.clearWatch();
                }
            }
        }, function (error) {
            $('#position-city').text('定位失败');
            console.log(error);
        });
    }

    //地址定位
    var cookie = $.AMUI.utils.cookie;
    if (!cookie.get('city') || cookie.get('geoCount') < 2) {
        geoLocationCity();
    }

    //手动定位
    $('#goto-position').click(function (e) {
        $('#position-city').text('定位中...');
        var city = geoLocationCity(true);
        e.stopPropagation();
    });
});